package cn.com.surker.sale.service.impl;

import cn.com.surker.common.Code;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.sale.dao.ContractDayPriceDao;
import cn.com.surker.sale.dao.SaleContractDao;
import cn.com.surker.sale.dao.SaleContractPaymentDao;
import cn.com.surker.sale.entity.ContractDayPrice;
import cn.com.surker.sale.entity.SaleContract;
import cn.com.surker.sale.entity.SaleContractPayment;
import cn.com.surker.sale.entity.SaleManRecord;
import cn.com.surker.sale.dao.SaleManRecordDao;
import cn.com.surker.sale.service.SaleManRecordBaseService;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import cn.com.surker.spring.RestResultDto;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
* <p>
    * 销售合同人员记录表 服务实现类
    * </p>
*
* @author admin
* @since 2024-08-03
*/
public abstract class SaleManRecordBaseServiceImpl extends ServiceImpl<SaleManRecordDao, SaleManRecord> implements SaleManRecordBaseService {

    @Resource
    protected SaleManRecordDao saleManRecordDao;
    @Resource
    protected SaleContractDao saleContractDao;
    @Resource
    protected DataSourceInfoDao dsDao;
    @Resource
    protected ContractDayPriceDao contractDayPriceDao;
    @Resource
    protected SaleContractPaymentDao contractPaymentDao;

    /**
     * 根据合同查询销售人员信息
     * @param contractId
     * @return
     */
    public List<SaleManRecord> findContract(Long contractId) {
        if (StringUtils.isAllParamNull(contractId))
            return null;
        QueryWrapper<SaleManRecord> query = new QueryWrapper<>();
        query.eq("status", 0);
        query.eq("contract_id", contractId);
        query.orderByDesc("create_time");
        List<SaleManRecord> list = saleManRecordDao.selectList(query);
        if (list == null || list.size() == 0)
            return null;
        return list;
    }

    /**
     * 新增历史记录
     * @param record
     * @return
     */
    public Integer saveRecord(SaleManRecord record) {
        if (record == null)
            return Code.PARAM_EMPTY.getCode();
        Integer code = saleManRecordDao.insert(record);
        if (code > 0) {
            UpdateWrapper<SaleContractPayment> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("sale", record.getSales());
            updateWrapper.eq("con_id", record.getContractId());
            updateWrapper.ge("pay_time", DateUtil.convertString(record.getTakeTime()));
            updateWrapper.eq("status", 0);
            code = contractPaymentDao.update(new SaleContractPayment(), updateWrapper);
            if (code > 0) {

                return 0;
            }
        }
        return -1;
    }

    /**
     * 根据合同信息批量新增
     * @param ids
     * @param newSales
     * @param takeTime
     * @param remark
     * @param creator
     * @return
     */
    public Integer updateBatchByContract(String ids, String newSales, String takeTime, String remark, String creator) {
        if (StringUtils.isAllParamNull(ids, newSales, takeTime))
            return Code.PARAM_EMPTY.getCode();
        String[] ids_ = ids.split(",");
        if (ids_ == null || ids_.length == 0)
            return Code.PARAM_EMPTY.getCode();
        QueryWrapper<SaleContract> contractQuery = new QueryWrapper<>();
        contractQuery.in("id", ids_);
//        contractQuery.eq("org_id", orgId);

        List<SaleContract> contractList = saleContractDao.selectList(contractQuery);
        if (contractList == null || contractList.size() == 0)
            return Code.NOT_CONTRACT_SALES.getCode();

        List<SaleManRecord> recordList = new ArrayList<>();
        Date nowDate = new Date();
        Date takeDate = DateUtil.convertDate(takeTime);
        for (int i = 0; i < contractList.size(); i++) {
            SaleContract contract = contractList.get(i);
            SaleManRecord record = new SaleManRecord(contract.getOrgId(), contract.getId(), contract.getName(),
                    newSales, takeDate, 0, remark, creator, nowDate);
            record.setOldSales(contract.getSales());
            recordList.add(record);
        }
        Integer code = saleManRecordDao.saveBatch(recordList);
        if (code > 0) {
            UpdateWrapper<SaleContract> up = new UpdateWrapper<>();
            up.set("sales", newSales);
            up.in("id", ids_);
//            up.eq("org_id", orgId);
            code = saleContractDao.update(new SaleContract(), up);
            if (code > 0) {
                UpdateWrapper<SaleContractPayment> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("sale", newSales);
                updateWrapper.in("con_id", ids_);
                updateWrapper.ge("pay_time", takeTime);
                updateWrapper.eq("status", 0);
                contractPaymentDao.update(new SaleContractPayment(), updateWrapper);

                UpdateWrapper<ContractDayPrice> uw = new UpdateWrapper<>();
                uw.set("salesman", newSales);
                uw.in("con_id", ids_);
                uw.ge("day", takeTime);
                contractDayPriceDao.update(new ContractDayPrice(), uw);
                String erpIds = "";
                for (int i = 0; i < contractList.size(); i++) {
                    SaleContract contract = contractList.get(i);
                    if (contract == null || StringUtils.isNull(contract.getErpid()))
                        continue;
                    erpIds += contract.getErpid() + ",";
                }
                erpIds = erpIds.substring(0, erpIds.length() - 1);
                updateErpContract(newSales, "", contractList.get(0).getOrgId(), erpIds);
                return 0;
            }
        }
        return -1;
    }

    /**
     * 批量修改销售人员记录
     * @param newSales
     * @param oldSales
     * @param takeTime
     * @param creator
     * @return
     */
    public Integer updateBatch(Long orgId, String newSales, String oldSales, String takeTime, String remark, String creator) {
        if (StringUtils.isAllParamNull(newSales, oldSales, takeTime, orgId))
            return Code.PARAM_EMPTY.getCode();
        QueryWrapper<SaleContract> contractQuery = new QueryWrapper<>();
        contractQuery.eq("sales", oldSales);
        contractQuery.eq("org_id", orgId);
        List<SaleContract> contractList = saleContractDao.selectList(contractQuery);
        if (contractList == null || contractList.size() == 0)
            return Code.NOT_CONTRACT_SALES.getCode();
        List<SaleManRecord> recordList = new ArrayList<>();
        Date nowDate = new Date();
        Date takeDate = DateUtil.convertDate(takeTime);
        String[] ids_ = new String[contractList.size()];
        for (int i = 0; i < contractList.size(); i++) {
            SaleContract contract = contractList.get(i);
            SaleManRecord record = new SaleManRecord(contract.getOrgId(), contract.getId(), contract.getName(),
                    newSales, takeDate, 0, remark, creator, nowDate);
            record.setOldSales(contract.getSales());
            recordList.add(record);
            ids_[i] = contract.getId() + "";
        }

        Integer code = saleManRecordDao.saveBatch(recordList);
        if (code > 0) {
            UpdateWrapper<SaleContract> up = new UpdateWrapper<>();
            up.set("sales", newSales);
            up.eq("sales", oldSales);
            up.eq("org_id", orgId);
            code = saleContractDao.update(new SaleContract(), up);
            if (code > 0) {
                UpdateWrapper<SaleContractPayment> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("sale", newSales);
                updateWrapper.in("con_id", ids_);
                updateWrapper.ge("pay_time", takeTime);
                updateWrapper.eq("status", 0);
                contractPaymentDao.update(new SaleContractPayment(), updateWrapper);

                UpdateWrapper<ContractDayPrice> uw = new UpdateWrapper<>();
                uw.set("salesman", newSales);
                uw.in("con_id", ids_);
                uw.ge("day", takeTime);
                contractDayPriceDao.update(new ContractDayPrice(), uw);
//                UpdateWrapper<ContractDayPrice> uw = new UpdateWrapper<>();
//                uw.set("salesman", newSales);
//                up.eq("salesman", oldSales);
//                up.eq("org_id", orgId);
//                contractDayPriceDao.update(new ContractDayPrice(), uw);
//                updateErpContract(newSales, oldSales, orgId, null);
                return 0;
            }
        }
        return -1;
    }

    private void updateErpContract(String newSales, String oldSales, Long orgId, String ids) {
        DataSourceInfo ds = dsDao.queryDSByOriginId(orgId);
        if (ds == null || ds.getStatus() == 1)
            return ;
        /**获取数据库联系信息**/
        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
        if (!StringUtils.isNull(ids)) {
            String sql = "update Market_Contract_T set salesman = '" + newSales + "' where id in (" + ids + ")";
            jdbcTemplate.update(sql);
        } else {
            String sql = "update Market_Contract_T set salesman = '" + newSales + "' where salesman = '" + oldSales + "'";
            jdbcTemplate.update(sql);
        }
    }

}